package com.suxii.netty_demo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.suxii.adapter.FriendListAdapter;
import com.suxii.netty_demo.R;
import com.suxii.service.MyNettyService;
import com.suxii.utils.Global;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FriendActivity extends AppCompatActivity {

    private RecyclerView friendList;
    private FriendListAdapter friendListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend);

        friendList=findViewById(R.id.friend_list);


        LinearLayoutManager manager=new LinearLayoutManager(this);
        friendList.setLayoutManager(manager);

        //new Thread(this::init).start();
        findFriend();

    }

    /*
    初始化，请求获取好友
     */
    private void init(){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getString(R.string.url)+"friend?uid="+ Global.uid)
                .get()
                .build();
        Call call = client.newCall(request);
        try {
            Response execute = call.execute();
            String s = execute.body().string();
            JsonObject jsonObject = new Gson().fromJson(s, JsonObject.class);
            String data =String.valueOf(jsonObject.get("data"));
            String[] uuid = new Gson().fromJson(data, String[].class);

            friendList.post(() -> {
                friendListAdapter = new FriendListAdapter(List.of(uuid), this);
                friendList.setAdapter(friendListAdapter);

                Intent intent=new Intent(this, MyNettyService.class);
                startService(intent);

                savaFriend(uuid);
                //findFriend();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    将请求的好友储存在本地
     */
    private boolean savaFriend(String[] uuid){
        File file = new File(this.getFilesDir(), "friend.sx");
        try(var fos=new FileOutputStream(file);
            var bw=new BufferedWriter(new OutputStreamWriter(fos))) {
            Arrays.stream(uuid).forEach(u->{
                try {
                    bw.write(u);
                    bw.newLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /*
    读取本地好友
     */
    private void findFriend(){
        File file = new File(this.getFilesDir(), "friend.sx");
        // 本地有缓存就加载本地，否就请求好友
        if (file.isFile()) {

            try (var fis = new FileInputStream(file);
                 var br = new BufferedReader(new InputStreamReader(fis))
            ) {
                String data;
                List<String> uuid = new ArrayList<>();
                while ((data = br.readLine()) != null) {
                    uuid.add(data);
                }
                //添加列表
                friendListAdapter = new FriendListAdapter(uuid, this);
                friendList.setAdapter(friendListAdapter);

                // 开启服务
                Intent intent=new Intent(this, MyNettyService.class);
                startService(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            new Thread(this::init).start();
        }
    }

    public void to_message(View view) {
        Intent intent = new Intent(this, MessageActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}